local function scanap()
  dofile('help/updatefile.lc')('tmp/aplist.lc', {status=1})
  collectgarbage()

  wifi.sta.getap(function(table)
    collectgarbage()
    local aptable = {}
		for ssid,v in pairs(table) do
			local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
			aptable[ssid] = {
				authmode = authmode,
				rssi = rssi,
				bssid = bssid,
				channel = channel
      }
      authmode = nil
      rssi = nil
      bssid = nil
      channel = nil
    end

    dofile('help/updatefile.lc')('tmp/aplist.lc', {status=0,data=aptable})

    aptable = nil
    collectgarbage()
  end)
end

return function (conn, req, args)
  dofile("server/header.lc")(conn, 200, 'json')

  if req.getRequestData().update then
    scanap()
    conn:send(sjson.encode({status=1}))
    collectgarbage()
    return
  end

  local info = {}
  if file.exists('tmp/aplist.lc') then
    info = dofile('tmp/aplist.lc')
  else
    scanap()
    info.status = 1
  end

  conn:send(sjson.encode(info))

  info = nil
  collectgarbage()
end